/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.nmp.controller;

/**
 *
 * @author ngotandieu
 */

import com.nmp.common.CommonUtil;
import com.nmp.common.RenderModel;
import com.nmp.model.SessionModel;
import com.nmp.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class IndexController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(IndexController.class);
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("IndexController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch(pathInfo) {
            case "/oauth2callback":
                content = renderOauth2CbPage(req, resp);
                break;
            case "/logout":
                content = doLogout(req, resp);
                break;
            case "/ajax-do-login":
                content = ajaxDoLogin(req, resp);
                break;
            default:  
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";
        TemplateDataDictionary dic = TemplateDictionary.create();

        try {
            dic.setVariable("HEADER", CommonUtil.getHeader());
            dic.setVariable("FOOTER", CommonUtil.getFooter());
            dic.setVariable("MENU", CommonUtil.getMenu(req));
            
            boolean isLogin = CommonUtil.checkSession(req, resp);
            if(!isLogin) {
                dic.showSection("IS_NOT_LOGIN");
            }
            
            Template template = RenderModel.getCTemplate("index_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("IndexController.renderIndexPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }
    
    private String renderOauth2CbPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "<script type=\"text/javascript\">"
                        + "window.opener.register.ggOauthCb(location.hash);"
                        + "window.close();"
                        + "</script>";
        return content;
    }

    private String doLogout(HttpServletRequest req, HttpServletResponse resp) {
        try {
            SessionModel sessionModel = SessionModel.getInstance();
            sessionModel.deleteSession(req, resp);
            resp.sendRedirect("/");
        } catch (IOException ex) {
            logger.error("IndexController.doLogout:" + ex.getMessage(), ex);
        }
        return "";
    }

    private String ajaxDoLogin(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        int error = -1;
        String msg = "Đăng nhập không thành công";
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        try {
            String u = req.getParameter("u") != null ? req.getParameter("u") : "";
            String p = req.getParameter("p") != null ? req.getParameter("p") : "";
            UserModel userModel = UserModel.getInstance();
            if (!u.equalsIgnoreCase("") && !p.equalsIgnoreCase("")) {
                String accountId = userModel.validateUser(u, p);
                if (!accountId.equalsIgnoreCase("")) {
                    error = 0;
                    msg = "Đăng nhập thành công";
                    SessionModel sessionModel = SessionModel.getInstance();
                    sessionModel.setSession(accountId, req, resp);
                }
            }
            content = CommonUtil.toJSON(error, msg);
        } catch (Exception ex) {
            logger.error("IndexController.ajaxDoLogin:" + ex.getMessage(), ex);
        }
        return content;
    }
}
